function [epos,notnans] = cvc_edat_trial_to_eeg_epoch(EEG,trials)
% CVC_EDAT_TRIAL_TO_EDAT_TRIALS
%
%  Synopsis
%  ========
%
%  [epos,notnans] = cvc_edat_trial_to_eeg_epoch(EEG,trials)
% 
%  -- Author: Mads Dyrholm --
%     Center for Visual Cognition, University of Copenhagen.
%     September 2011
%
%  Purpose
%  =======
%
%  Find EEG epoch numbers corresponding to edat trial numbers.
%
%  Output
%  ======
%
%  epos - List of EEG epochs corresponding to the trial numbers given.
%  a nan will be inserted if the EEG epoch is missing.
%
%  notnans - Indices of the non-nan epoch numbers.

if isempty(EEG.epoch)
  error('This dataset has no epoch structure.');
end
% 

epoev = [];
for epo=1:EEG.trials
  tmp = min(find([EEG.epoch(epo).eventlatency{:}]==0));
  tmp2 = EEG.epoch(epo).eventtrial{tmp};
  if ~isnumeric(tmp2)
    tmp2 = str2num(tmp2);
  end
  epoev = cat(2,epoev,tmp2);
end

epos = [];
for trial = trials
  tmp = find(trial==epoev);
  if isempty(tmp), tmp=nan; end
  epos = cat(2,epos,tmp);
end

notnans = find(~isnan(epos));
